import lodash from 'lodash'

const strTrim = (a) => String(a).replace(/^\s+|\s+$/g, '')

// @a -> str, b -> no html entities?
const strQuot = (a, b) => {
	a = String(a)
	b && (a = a.replace(/<[^>]+>/g, ''))
	return a.replace(/\"/g, '&quot;')
}

// 在a中取以b开始的字符串(不包括b) /@ c -> last indexOf ?
const strFrom = (a, b, c) => {
  let d = c ? a.lastIndexOf(b) : a.indexOf(b)
  return d < 0 ? '' : a.substr(d + b.length)
}

// 在a中取以b结束的字符串(不包括b) /@ c -> last indexOf ?
const strTo = (a, b, c) => {
  let d = c ? a.lastIndexOf(b) : a.indexOf(b)
  return d < 0 ? '' : a.substr(0, d)
}

// 取字符串字节数(一个汉字算双字节)  /@ s -> str, b -> 一个汉字算几个字节？默认2个
const strLen = (s, b) => {
  if (!s) return 0;
  if (!b) b = $.x.cnBytes || 2;
  let d = 0
  for (let i = 0, l = s.length; i < l; i++)
    d += s.charCodeAt(i) > 128 ? b : 1;
  return d;
}

// 数字前加0  /@ a -> num, b -> 补成多少长度的字符串？
const strPad = function(a, b, c) {
	c = c == null ? '0' : (c + '');
	if (!b)
		return a < 10 ? c + a : a;
	a = a + '';
	while (a.length < b)
		a = c + a;
	return a
}

const strFormat = (a, b, c, d) => {
  a != null && (a += '');
  if (!a || !b) return a;
  if (Array.isArray(b)) {
    return a.replace(/\$\{?(\d+)\}?/g, function($0, $1) {
      return b[$1] == null ? (d ? $0 : '') : c ? encodeURIComponent(b[$1]) : b[$1]
    });
  } else {
    return a.replace(/\$\{?([a-z_][\w.]*)\}?/gi, function($0, $1) {
      let e = lodash.get(b, $1)
      return e == null ? (d ? $0 : '') : c ? encodeURIComponent(e) : e
    });
  }
}

const strEscape = function(s) {
	return s != null ? (s + '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;') : '';
}

// 在 a 中查找 b 并给 b 加上标签样式 c /@ a -> str, b -> key, c -> matchLength?, d -> key cls?
const strHighlight = function(a, b, c, d) {
	return (a = a + '').replace(RegExp('(<[\\/!]?\\w+(?::\\w+)?\\s*(?:[-\\w]+(?:=(\'|")?.*?\\2)?\\s*)*>)|(' + strSplitword(b, c, true).join('|') + ')', 'ig'), function($0, $1, $2, $3) {
	   	return $3 === undefined ? $1 : '<em class="' + (d || 'f-keyword') + '">' + $3 + '</em>'
	})
}

// 字符转为regexp支持的模式
const _s_regexp = function(a) {
	return a.replace(/([-.*+?^${}()|[\]\/\\])/g, '\\\$1')
}

// @a -> key, b -> matchLength, c -> regexp?
const strSplitword = function(a, b, c) {
	let e = [c ? _s_regexp(a) : a]
  let m = a.length
	if (b > 0 && m > b) {
		for (let j = m - 1; j >= b; j --) {
			for (let i = 0, l = m - j, f; i <= l; i ++) {
				f = a.substr(i, j)
				e.push(c ? _s_regexp(f) : f)
			}
		}
	}
	return e
}


export {strTrim, strEscape, strQuot, strFrom, strTo, strPad, strLen, strFormat, strHighlight}
